using System.Security.Claims;
using BootstrapBlazorApp.Server.Data;
using BootstrapBlazorApp.Server.Pojo;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using BootstrapBlazorApp.Server.Utils;
using Microsoft.AspNetCore.Authorization;

namespace BootstrapBlazorApp.Server.Controllers;

[ApiController]
[Route("/api/[controller]/[action]")]
public class AccountController:ControllerBase
{
    //注入相关的数据库服务实例使用
    private readonly IDataService<User> _userService;
    
    //自动查找注册到容器中的IDataService<User>服务
    public AccountController(IDataService<User> userService)
    {
        _userService = userService;
    }
    //增加API方法
    [HttpPost]
    public async Task<object> Login([FromBody] LoginVo loginVo)
    {
        var checkPassword=Md5Utils.Md5Encrypt32(loginVo.Password); 
        var user=await Data.User.Where(x => x.UserName == loginVo.UserName && x.Password==checkPassword).FirstAsync();
        //明文密码
        //var user=await Data.User.Where(x => x.UserName == loginVo.UserName && x.Password==loginVo.Password).FirstAsync();
        //查找不到对应用户
        if (user == null)
        {
            return new { Code = 500, Message = "用户名或密码错误" };
        }
        
        //创建包含用户认证的实例，用于cookie验证
        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
        //将新的声明添加到 ClaimsIdentity 对象中
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName!));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
        //用来登录用户
        await HttpContext.SignInAsync(new ClaimsPrincipal(identity), new AuthenticationProperties()
        {
            IsPersistent = true,
            ExpiresUtc = loginVo.IsKeep ? DateTimeOffset.Now.AddDays(1) : DateTimeOffset.Now.AddMinutes(30)
        });
        return new { Code = 200, Message = "登陆成功" };
    }
    
    //修改密码
    [HttpPost]
    public async Task<Object> ChangePassword([FromBody] ChangePasswordVo changePasswordVo)
    { 
        var user=await Data.User.Where(x => x.UserName == changePasswordVo.UserName).FirstAsync();
        if (user == null)
        {
            return new { Code = 500, Message = "用户名错误" };
        }

        user.Password = Md5Utils.Md5Encrypt32(changePasswordVo.Password);
        
        var regResult = await _userService.SaveAsync(user, ItemChangedType.Update); 
        if (!regResult)
        {
            return new { Code = 422, Message = "修改失败，请稍后再试" };
        }
        return new { Code = 200, Message = "修改密码成功" };
    }
    
    // 注册新用户的方法
    [HttpPost]
    public async Task<ActionResult<object>> Register([FromBody] RegisterVo registerVo)
    {
        var user=await Data.User.Where(x => x.UserName == registerVo.UserName).FirstAsync();
        //查找得到对应用户
        if (user != null)
        {
            return BadRequest(new { Code = 409, Message = "用户名已存在" });
        }
        //加密
        var changedPassword = Md5Utils.Md5Encrypt32(registerVo.Password); 

        // 创建新用户
        var newUser = new User
        {
            UserName = registerVo.UserName,
            Password = changedPassword,
            Avatar = "https://ww3.sinaimg.cn/mw690/d315af46ly1hnn5btbjr5j20j60j7mzv.jpg",
            NickName = registerVo.UserName
            
        };
        var regResult = await _userService.SaveAsync(newUser, ItemChangedType.Add); // ItemChangedType提示
        if (!regResult)
        {
            return new { Code = 422, Message = "注册失败，请稍后再试" };
        }
        
        return new { Code = 200, Message = "注册成功" };
    }

    //登出方法
    [HttpGet]
    [Authorize]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(); //清除所有用户认证相关信息，包括cookie
        return Redirect("/Login");   //重定向
    }
}